  {  Petrova Tatjana
     2012/10/29
     This program writes the sum of  polynomials .}
program polynomials;

{$APPTYPE CONSOLE}

uses
  SysUtils;
type
  pelement=^element;
  element=record
    value:integer;
    value2:integer;
    next:pelement;
  end;
procedure AddToBegin(var head:pelement;num,num1:integer);
var
  tmp : pelement;
begin
  tmp := head;
  new(head);
  head^.value := num;
  head^.value2 := num1;
  head^.next := tmp;
end;

procedure AddToEnd (var head:pelement;
                        num,num1 : integer);
var
  current : pelement;
begin
  if(head<>nil) then
  begin
    current:=head;
    while(current^.next<>nil)do
      current := current^.next;
    new(current^.next);
    current^.next^.value:=num;
    current^.next^.value2:=num1;
    current^.next^.next:=nil
  end else
    AddToBegin(head,num,num1);
  end;

procedure printList (head : pelement);
var
  current : pelement;
begin
  current := head;
  while(current<>nil) do
  begin
    writeln(current^.value,' ',current^.value2);
    current := current^.next;
  end;
end;


procedure  SumOfPolynomials (var head:pelement);
var
  N,N1,i,c,d,e,e1,f,f1:integer;
  fin:textFile;
  temp:pelement;
begin
  assignFile(fin,'input.txt');
  reset(fin);
  readln(fin,N);
  for i:=1 to N do
  begin
    readln(fin,c,d);
    AddToEnd(head,c,d);
  end;
  readln(fin,N1);
  for i:=1 to N1 do
  begin
    readln(fin,c,d);
    AddToEnd(head,c,d);
  end;
  for i:=1 to(N+N1) do
  begin
    if(head^.value<head^.next^.value)then
    begin
      e:=head^.value;
      f:=head^.value2;
      e1:= head^.next^.value;
      f1:= head^.next^.value2;
      head^.value:=e1;
      head^.value2:=f1;
      head^.next^.value:=e;
      head^.next^.value2:=f;
    end;
  end;
  for i:=1 to(N+N1) do
  begin
    if(head^.value2=head^.next^.value2) then
    begin
       head^.next^.value:= head^.value+head^.next^.value;
       temp:=head^.next;
       dispose(head);
       head:=temp;
    end;
  end;



  printlist(head);
  closefile(fin);
end;
var
  head:pelement;


begin
  SumOfPolynomials(head);
  readln;
end.

